/**
 * 签到相关的验证 Schema
 */

import { Type, Static } from '@sinclair/typebox'
import { UUIDSchema, LocationSchema, URLSchema, RecordStatusSchema, PaginationQuerySchema } from './common.schema'

// ==================== 执行签到 ====================

/**
 * 执行签到请求
 */
export const PerformCheckInSchema = Type.Object(
    {
        eventId: UUIDSchema,
        memberId: UUIDSchema,
        location: Type.Optional(LocationSchema),
        photo: Type.Optional(URLSchema),
        secretCode: Type.Optional(
            Type.String({
                pattern: '^\\d{6}$',
                description: '6位数字签到码'
            })
        ),
        checkInTime: Type.Optional(
            Type.String({
                format: 'date-time',
                description: '签到时间（默认为当前时间）'
            })
        )
    },
    {
        $id: 'PerformCheckIn',
        description: '执行签到请求'
    }
)

export type PerformCheckInRequest = Static<typeof PerformCheckInSchema>

/**
 * 签到结果响应
 */
export const CheckInResultSchema = Type.Object(
    {
        success: Type.Literal(true),
        data: Type.Object({
            success: Type.Boolean({ description: '签到是否成功' }),
            status: RecordStatusSchema,
            message: Type.String({ description: '签到结果信息' }),
            eventRecordId: Type.Optional(UUIDSchema),
            failedConditions: Type.Optional(
                Type.Array(Type.String(), {
                    description: '未满足的签到条件'
                })
            )
        })
    },
    {
        $id: 'CheckInResult',
        description: '签到结果响应'
    }
)

// ==================== 执行签退 ====================

/**
 * 执行签退请求
 */
export const PerformCheckOutSchema = Type.Object(
    {
        eventInstanceId: UUIDSchema,
        memberId: UUIDSchema,
        checkOutTime: Type.Optional(
            Type.String({
                format: 'date-time',
                description: '签退时间（默认为当前时间）'
            })
        ),
        reason: Type.Optional(
            Type.String({
                maxLength: 200,
                description: '签退原因'
            })
        )
    },
    {
        $id: 'PerformCheckOut',
        description: '执行签退请求'
    }
)

export type PerformCheckOutRequest = Static<typeof PerformCheckOutSchema>

// ==================== 管理员补签 ====================

/**
 * 管理员补签请求
 */
export const ManualCheckInSchema = Type.Object(
    {
        eventId: UUIDSchema,
        memberId: UUIDSchema,
        status: RecordStatusSchema,
        reason: Type.String({
            minLength: 1,
            maxLength: 200,
            description: '补签原因'
        }),
        adminId: UUIDSchema
    },
    {
        $id: 'ManualCheckIn',
        description: '管理员补签请求'
    }
)

export type ManualCheckInRequest = Static<typeof ManualCheckInSchema>

// ==================== 签到汇总 ====================

/**
 * 事件签到汇总响应
 */
export const EventStatisticsSchema = Type.Object(
    {
        success: Type.Literal(true),
        data: Type.Object({
            totalParticipants: Type.Integer({ description: '总参与人数' }),
            presentCount: Type.Integer({ description: '准时签到人数' }),
            lateCount: Type.Integer({ description: '迟到人数' }),
            absentCount: Type.Integer({ description: '缺席人数' }),
            pendingCount: Type.Integer({ description: '待签到人数' }),
            leaveEarlyCount: Type.Integer({ description: '早退人数' }),
            attendanceRate: Type.Number({ description: '出勤率（百分比）' })
        })
    },
    {
        $id: 'EventStatistics',
        description: '事件签到汇总'
    }
)

// ==================== 签到历史 ====================

/**
 * 签到历史查询参数
 */
export const CheckInHistoryQuerySchema = Type.Intersect(
    [
        PaginationQuerySchema,
        Type.Object({
            memberId: UUIDSchema,
            eventId: Type.Optional(UUIDSchema),
            status: Type.Optional(
                Type.Array(RecordStatusSchema, {
                    description: '筛选状态（可多选）'
                })
            ),
            startDate: Type.Optional(
                Type.String({
                    format: 'date-time',
                    description: '开始日期'
                })
            ),
            endDate: Type.Optional(
                Type.String({
                    format: 'date-time',
                    description: '结束日期'
                })
            )
        })
    ],
    {
        $id: 'CheckInHistoryQuery',
        description: '签到历史查询参数'
    }
)

export type CheckInHistoryQuery = Static<typeof CheckInHistoryQuerySchema>

/**
 * 考勤记录项
 */
export const AttendanceRecordSchema = Type.Object(
    {
        id: UUIDSchema,
        eventId: UUIDSchema,
        eventTitle: Type.String({ description: '活动标题' }),
        memberId: UUIDSchema,
        memberName: Type.String({ description: '成员姓名' }),
        status: RecordStatusSchema,
        checkInTime: Type.Optional(Type.String({ format: 'date-time' })),
        checkOutTime: Type.Optional(Type.String({ format: 'date-time' })),
        location: Type.Optional(LocationSchema),
        photo: Type.Optional(URLSchema),
        isManual: Type.Boolean({ description: '是否管理员补签' }),
        reason: Type.Optional(Type.String({ description: '原因（补签/签退）' }))
    },
    {
        $id: 'AttendanceRecord',
        description: '考勤记录'
    }
)

/**
 * 签到历史响应
 */
export const CheckInHistoryResponseSchema = Type.Object(
    {
        success: Type.Literal(true),
        data: Type.Object({
            data: Type.Array(AttendanceRecordSchema),
            total: Type.Integer(),
            offset: Type.Integer(),
            limit: Type.Integer(),
            hasMore: Type.Boolean()
        })
    },
    {
        $id: 'CheckInHistoryResponse',
        description: '签到历史响应'
    }
)

// ==================== 批量初始化 ====================

/**
 * 批量初始化签到记录请求
 */
export const InitializeCheckInSchema = Type.Object(
    {
        eventId: UUIDSchema,
        source: Type.Union([Type.Literal('groups'), Type.Literal('members')], {
            description: '数据来源：groups（从群组） 或 members（从成员列表）',
            default: 'groups'
        })
    },
    {
        $id: 'InitializeCheckIn',
        description: '批量初始化签到记录'
    }
)

export type InitializeCheckInRequest = Static<typeof InitializeCheckInSchema>

/**
 * 批量初始化结果
 */
export const InitializeResultSchema = Type.Object(
    {
        success: Type.Literal(true),
        data: Type.Object({
            created: Type.Integer({ description: '新创建的记录数' }),
            skipped: Type.Integer({ description: '跳过的记录数' }),
            total: Type.Integer({ description: '总参与人数' })
        })
    },
    {
        $id: 'InitializeResult',
        description: '批量初始化结果'
    }
)
